<template>
  <div style="margin: 20px auto 5px;width: 85%;box-sizing: border-box;">
    <a-spin :spinning="ythLoading">
      <a-form-model class="user-layout-login" @keyup.enter.native="handleSubmit">
        <login-account
          ref="alogin"
          @validateFail="validateFail"
          @success="requestSuccess"
          @fail="requestFailed"
        ></login-account>
        <a-form-item style="margin-top: 13px;margin-bottom: unset !important;">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="loginBtn"
            @click.stop.prevent="handleSubmit"
            :disabled="loginBtn"
          >登录
          </a-button>
        </a-form-item>
      </a-form-model>
      <login-select-tenant ref="loginSelect" @success="loginSelectOk"></login-select-tenant>
    </a-spin>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  ACCESS_TOKEN,
  ENCRYPTED_STRING, OAUTH2,
  UI_CACHE_DB_DICT_DATA,
  USER_DEPARTS,
  USER_INFO,
  USER_NAME
} from '@/store/mutation-types'
import { getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { timeFix, welcome } from '@/utils/util'
import LoginAccount from './LoginAccount'
import LoginSelectTenant from './LoginSelectTenant'
import { getAction, postAction } from '@/api/manage'
import store from '@/store'

export default {
  components: {
    LoginAccount,
    LoginSelectTenant
  },
  data() {
    return {
      state: 99,
      responseType: 'code',
      ythLoading: false,
      rememberMe: false,
      loginBtn: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      url: {
        oauth2: '/idp/oauth2/authorize',
        oAuthLogin: '/sys/oAuthLogin'
      },
      encryptedString: {
        key: '',
        iv: ''
      }
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
    this.rememberMe = true
  },
  mounted() {
    if (this.$route.query.code && this.$route.query.state == this.state) {
      this.ythLoading = true
      getAction(this.url.oAuthLogin, { code: this.$route.query.code }).then(res => {
        if (res.success) {
          const result = res.result
          const userInfo = result.userInfo
          Vue.ls.set(OAUTH2, this.$route.query.state)
          Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(USER_DEPARTS, result.departs[0], 7 * 24 * 60 * 60 * 1000)
          Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
          store.commit('SET_TOKEN', result.token)
          store.commit('SET_INFO', userInfo)
          store.commit('USER_DEPARTS', result.departs[0])
          store.commit('SET_NAME', { username: userInfo.username, realname: userInfo.realname, welcome: welcome() })
          store.commit('SET_AVATAR', userInfo.avatar)
          this.requestSuccess(res.result)
        } else {
          this.ythLoading = false
          window.location.href = window._CONFIG['oauth2OutPrefixUrl'] + `?redirctToUrl=${window.location.protocol}//${window.location.host}/noPermission&entityId=${process.env.VUE_APP_OAUTH2_CLIENT_ID}&redirectToLogin=true`

          // window.open('/noPermission', '_self')
          // this.requestFailed(res)
        }
      })
    }
  },
  methods: {
    handleRememberMeChange(e) {
      this.rememberMe = e.target.checked
    },
    /**跳转到登录页面的参数-账号获取*/
    getRouterData() {
      this.$nextTick(() => {
        let temp = this.$route.params.username || this.$route.query.username || ''
        if (temp) {
          this.$refs.alogin.acceptUsername(temp)
        }
      })
    },

    //登录
    handleSubmit() {
      this.loginBtn = true
      this.$refs.alogin.handleLogin(this.rememberMe)
    },

    handleOAuthLogin() {
      window.location.href = window._CONFIG['oauth2PrefixUrl'] + `?redirect_uri=${window.location.protocol}//${window.location.host}/user/login&state=${this.state}&client_id=${process.env.VUE_APP_OAUTH2_CLIENT_ID}&response_type=${this.responseType}`
    },

    // 校验失败
    validateFail() {
      this.loginBtn = false
    },

    // 登录后台成功
    requestSuccess({ roles, passOut }) {
      console.log(passOut)
      Vue.ls.set('passOut', passOut)
      this.roleResolve(roles[0]).then(() => {
        this.loginSelectOk()
      })

    },
    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '登录失败',
        description: description,
        duration: 4
      })
      //账户密码登录错误后更新验证码
      this.$refs.alogin.handleChangeCheckCode()
      this.loginBtn = false
    },
    loginSelectOk() {
      this.loginSuccess()
    },
    //登录成功
    loginSuccess() {
      this.$router.push({ path: '/dashboard/analysis' }).catch(() => {
        console.log('登录跳转首页出错,这个错误从哪里来的')
      })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },

    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    //获取密码加密规则
    getEncrypte() {
      var encryptedString = Vue.ls.get(ENCRYPTED_STRING)
      if (encryptedString == null) {
        getEncryptedString().then((data) => {
          this.encryptedString = data
        })
      } else {
        this.encryptedString = encryptedString
      }
    },
    roleResolve({ roleId }) {
      return new Promise((resolve, reject) => {
        let obj = {
          roleId: roleId
        }
        Vue.ls.set('RoleId', roleId)
        getAction('/sys/user/updateRoleStatus', obj).then(res => {
          if (res.success) {
            resolve()
          }
        })
      })
    }
  }
}
</script>
<style lang='less' scoped>
.user-layout-login {
  //height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;

  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 15px;
    height: 40px;
    width: 100%;
    background-color: #17448e;
    border-color: #17448e;
  }

  .yth-button {
    padding: 0 15px;
    margin-top: 10px;
    height: 40px;
    width: 100%;
    font-size: 15px;
    color: #1961AC;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }

  .explanatory-text {
    width: 100%;
    color: #e82221;
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center;
    font-family: "楷体", "KaiTi", "楷体_GB2312", "楷体_GBK", sans-serif;
    font-size: 14px;
    font-weight: bold;
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>